package com.dymall.config;

import cn.hutool.core.collection.CollUtil;
import com.dymall.interceptor.LoginInterceptor;
import com.dymall.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration //表明这是一个配置类，Spring 会根据这个类来创建 Bean 定义并注册到容器中
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)//启用 AuthProperties 类作为配置属性类，并将其绑定到 Spring 环境中
public class MvcConfig implements WebMvcConfigurer {
    //实现了 WebMvcConfigurer 接口，主要用于配置和注册拦截器

   private final JwtTool jwtTool;
   private final AuthProperties authProperties;
   private final StringRedisTemplate stringRedisTemplate;

/*    @Bean
    public CommonExceptionAdvice commonExceptionAdvice(){
        return new CommonExceptionAdvice();
    }*/

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 1.添加拦截器
        // 1.1、使用 jwtTool 初始化 LoginInterceptor，用于在请求到达控制器前进行身份验证
        LoginInterceptor loginInterceptor = new LoginInterceptor(jwtTool, stringRedisTemplate);
        // 1.2、将 loginInterceptor 注册到 Spring MVC 框架中，以便它可以拦截请求
        InterceptorRegistration registration = registry.addInterceptor(loginInterceptor);

        // 2.配置拦截路径
        // 从 authProperties 获取需要保护的路径列表，并将这些路径添加到拦截器的拦截路径中
        List<String> includePaths = authProperties.getIncludePaths();
        if (CollUtil.isNotEmpty(includePaths)) {
            registration.addPathPatterns(includePaths);
        }

        // 3.配置放行路径
        // 从 authProperties 获取不需要保护的路径列表，并将它们排除出拦截器的拦截范围
        List<String> excludePaths = authProperties.getExcludePaths();
        if (CollUtil.isNotEmpty(excludePaths)) {
            registration.excludePathPatterns(excludePaths);
        }

        //手动排除了一些通常不需要身份验证的路径
        registration.excludePathPatterns(
                "/error",
                "/favicon.ico",
                "/v2/**",
                "/v3/**",
                "/swagger-resources/**",
                "/webjars/**",
                "/doc.html"
                );

    }
}
